#include <Arduino.h>

#ifndef _SOFT_USB_HOST_H
#define _SOFT_USB_HOST_H

extern "C" {
#include "usb_host.h"
}

struct USBMessage;

// 引脚（最多支持4个软件USB）
typedef struct
{
    int dp0;
    int dm0;
    int dp1;
    int dm1;
    int dp2;
    int dm2;
    int dp3;
    int dm3;
} usb_pins_config_t;

#if !defined USE_NATIVE_GROUP_TIMERS

typedef struct
{
    int type; // the type of timer's event
    int timer_group;
    int timer_idx;
    uint64_t timer_counter_value;
} timer_event_t;
static xQueueHandle timer_queue = NULL;

#endif

void IRAM_ATTR timer_group0_isr(void *para);

class SOFT_USB_HOST {
  public:
    bool init(usb_pins_config_t pconf);

    void setActivityBlinker(onledblinkcb_t onActivityCB);
    void setTaskPriority(uint8_t p) { priority = p; };
    void setTaskCore(uint8_t c) { core = c; }
    void setISRAllocFlag(int alloc_flags);

    void connectToClient();

    static void TimerTask(void *arg);

    // 使用这2个函数以避免"Guru Meditation Error: Core 1 panic'ed (Cache disabled but cached memory region accessed)"
    // 在执行高优先级任务（如 SD 卡读写、Wi-Fi 传输）时，暂停 USB 定时器以防止中断干扰
    void TimerPause();
    void TimerResume();

  private:
    bool inited = false;
    bool paused = false;
    uint8_t priority = 5;
    uint8_t core = 1;
    int intr_alloc_flags = ESP_INTR_FLAG_IRAM;
    bool _init(usb_pins_config_t pconf);
    static void onUSBMessageDecode(uint8_t src, uint8_t len, uint8_t *data);
    
};

extern SOFT_USB_HOST _sUSBHost;

#endif
